package com.gztms.usermgnt.service.impl;

import com.gztms.usermgnt.mapper.UserMapper;
import com.gztms.usermgnt.pojo.LoginUser;
import com.gztms.usermgnt.pojo.User;
import com.gztms.usermgnt.service.LoginService;
import com.gztms.usermgnt.service.UserService;
import com.gztms.utils.JwtUtil;
import com.gztms.utils.RedisCache;
import com.gztms.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Zoey
 * @date 2023/3/8 1:04
 * @Description
 **/
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 登录方法
     * @param user
     * @return
     */
    @Override
    public ResultUtil login(User user) {
        // 1、获取AuthenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUid(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // 2、认证
        // 2.1 认证不通过，返回提示信息
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登陆失败");
        }
        // 2.2 认证通过，使用uid生成jwt
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String uid = loginUser.getUser().getUid();
//        String jwt = JwtUtil.createJWT(uid);
        Long time = (long) (24 * 60 * 60 * 1000);
        String jwt = JwtUtil.createJWT(uid, time);
        // 2.3 把完整的用户信息存入redis中，uid作为key
        redisCache.setCacheObject("login:"+uid, loginUser);


        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResultUtil(ResultUtil.SUCCESS,"登陆成功",map);
    }

    @Override
    public ResultUtil logout() {
        // 获取SecurityContextHolder的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String uid = loginUser.getUser().getUid();

        // 删除redis中的值
        redisCache.deleteObject("login:"+uid);
        return new ResultUtil(ResultUtil.SUCCESS,"注销成功");
    }

    @Override
    public ResultUtil getUserInfo(String token) {
        // 根据token获取用户个人信息
        String uid = null;
        try {
            uid = JwtUtil.parseJWT(token).getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (uid == null){
            return new ResultUtil(ResultUtil.SERVER_ERROR,"无效token");
        }

        Map<String,String> map = new HashMap<>();
        // 从uid查询到用户名
        map.put("uid",uid);
        // 从数据库中查询头像信息，用户名
        User user = userMapper.selectById(uid);
        String url = user.getAvatar();
        String username = user.getUsername();
        map.put("avatar",url);
        map.put("username",username);
        log.info("userinfo:", map);
        return new ResultUtil(ResultUtil.SUCCESS,"登录信息获取成功",map);
    }


}
